package com.zerosky.crm.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.zerosky.crm.util.BaseAction;
import com.zerosky.crm.util.IMGTOOL;
import com.zerosky.crm.util.MyFileUploadUtils;

/**
 * 上传控制器
 * 
 * @author hugy
 * 
 */
@Controller
@RequestMapping(value = "Upload")
public class UploadController extends BaseAction {

	/**
	 * 文件上传
	 * 
	 * @throws IOException
	 */
	@RequestMapping("/upload.do")
	public String uploadCertificate(@RequestParam("uploadFile") MultipartFile file, HttpServletResponse response,
			HttpServletRequest request, HttpSession session) throws IOException {

		Map map = new HashMap();
		// 获取tmacat中的项目路径
		// String basePath = request.getSession().getServletContext()
		// .getRealPath("//saituImage");
		// 定义一个图片路径来获取图片的相对路径
		// String fileUrl = "";
		// Long time = new Date().getTime();
		// String base = request.getScheme() + "://" + request.getServerName()
		// + ":" + request.getServerPort() + request.getContextPath()
		// + "/upload";
		// fileUrl = getFileUrl(file, basePath, time,response,request);
		//
		// // 图片信息存入到seesion中
		// if (!request.getParameter("count").equals("0")) {
		// List<Picture> list = null;
		// if (session.getAttribute("PictureList") != null) {
		// list = (List<Picture>) session.getAttribute("PictureList");
		// } else {
		// list = new ArrayList<Picture>();
		// }
		// Picture entity = new Picture();
		// entity.setUrl("/upload"+fileUrl);
		// entity.setPictureName(file.getName());
		// entity.setStatus("0");
		// if (request.getParameter("type").equals("station")) {
		// entity.setType("0");
		// } else {
		// entity.setType("1");
		// }
		//
		// list.add(entity);
		// //session.setAttribute("PictureList", list);
		// }

		// if (!fileUrl.equals("-1")) {
		// map.put("url", "saituImage"+fileUrl);
		// //json.put("path", base+fileUrl);
		// map.put("code", 0);
		// } else {
		// map.put("code", 1);
		// }
		try {
			String path = "saituImage/";
			//MyFileUploadUtils.saveFileName(request, file, path);
			map.put("url", path + MyFileUploadUtils.saveFileName(request, file, path));
			map.put("code", 0);
		} catch (Exception e) {
			map.put("code", 1);
		}
		feedback(response, toJson(map));
		return null;
	}

	public String getFileUrl(MultipartFile file, String basePath, Long time, HttpServletResponse response,
			HttpServletRequest request) {
		// 定义一个图片路径来获取图片的相对路径
		String fileUrl = "";
		try {
			CommonsMultipartFile cf = (CommonsMultipartFile) file;
			DiskFileItem fi = (DiskFileItem) cf.getFileItem();
			File f = fi.getStoreLocation();
			if (!file.isEmpty()) {

				// 创建文件夹
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
				String ymd = sdf.format(new Date());
				// 图片路径
				fileUrl = "/" + ymd + "/" + time + "_" + file.getOriginalFilename();

				String fileurl = basePath + "/" + ymd;
				File saveDirFile = new File(fileurl);
				// 判断文件是否存在，否，则创建文件
				if (!saveDirFile.exists())
					saveDirFile.mkdirs();
				// 拿到输出流，同时重命名上传的文件
				basePath += fileUrl;
				FileOutputStream os = new FileOutputStream(basePath);
				// 拿到上传文件的输入流
				FileInputStream in = null;
				in = new FileInputStream(f);
				// 读取文件
				byte[] buf = new byte[1024];
				int length = 0;
				while ((length = in.read(buf)) != -1) {
					os.write(buf, 0, length);
				}
				in.close();
				// 关闭IO流
				os.flush();
				os.close();

				String shops = request.getParameter("type");
				if (shops != null && "shops".equals(shops)) {
					if (!"".equals(file.getOriginalFilename()) && file.getOriginalFilename().indexOf("") != -1) {
						// 压缩图片
						List list1 = IMGTOOL
								.compressPic(fileurl + "/", fileurl + "/compressPic/",
										time + "_" + file.getOriginalFilename(),
										time + "_"
												+ file.getOriginalFilename().substring(0,
														file.getOriginalFilename().lastIndexOf("."))
												+ "compressPic"
												+ file.getOriginalFilename()
														.substring(file.getOriginalFilename().lastIndexOf(".")),
										600, 600);
						String compressPicPath = list1.get(0).toString();// 压缩后图片路径
						String cutPicPath = "/compressPic/cutPicture/" + time + "_"
								+ file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."))
								+ "cut"
								+ file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));// 裁剪后图片路径
						boolean aaa = IMGTOOL.cutPic(fileurl + compressPicPath, fileurl + cutPicPath, 20, 20,
								Integer.parseInt(list1.get(1).toString()), Integer.parseInt(list1.get(2).toString()));
						// 判断压缩、剪切是否出错
						if (!aaa || "-1".equals(list1.get(3).toString())) {
							fileUrl = "-1";
						}
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			fileUrl = "-1";
		}

		return fileUrl;

	}    

}
